package com.oceansoft.mobile.econsole.modules.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.constant.Constant;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.StringUtils;
import com.oceansoft.mobile.econsole.modules.api.service.ISmsService;
import com.oceansoft.mobile.econsole.modules.api.util.ApiCodeToMessageUtil;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.SMSMessage;
import org.apache.taglibs.standard.tag.common.core.Util;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Random;

import static com.oceansoft.mobile.econsole.common.constant.Constant.BIZ_DICT;

/**
 * 验证码生成业务组件
 *
 * @author chenw
 * @time 2014-08-25
 */
@Service
public class SmsSendServiceImpl extends CacheBaseService implements ISmsService {

    @Override
    public Result createValidateCode(String smsType, String telNum, String content, long exprire) throws IOException {
        String _key = String.format("sms:code:%s:%s", smsType, telNum);
        long _expires = getExpires(_key);
        if (_expires > 0) {
            return new Result(Result.FAILURE, String.format("请%s秒后重新获取！", _expires));
        } else {
            long _code;
            do {
                _code = new Random(System.currentTimeMillis()).nextInt(1000000);
            } while (_code < 100000);
//            String msg = content + _code;
            //重新请求一次并返回结果
            String resp = HttpClientUtil.doGet(super.configInfo.getGAApiUrl("Message.aspx", "hm", telNum, "msg", Util.URLEncode((content + _code), "utf-8")));
            //判断是否为空
            if (StringUtils.isNotBlank(resp)) {
                JSONObject data = JSON.parseObject(resp);
                boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
                //是否请求成功
                if (succ) {
                    super.cache(_key, String.valueOf(_code), exprire);
                    return new Result(Result.SUCC, "验证码获取成功");
                } else {
                    return new Result(Result.FAILURE, data.getString("msg"), "验证码获取失败");
                }
            }
            return new Result(Result.FAILURE, "验证码获取失败");
        }
    }

    @Override
    public String getValidateCode(int bizType, String telNum) {
        return super.get(String.format("sms:code:%s:%s", BIZ_DICT.get(bizType), telNum));
    }

    @Override
    public void clearValidateCode(int bizType, String telNum) {
        super.delCache(String.format("sms:code:%s:%s", BIZ_DICT.get(bizType), telNum));
    }

    @Override
    public Result sendCodeMsg(String phone, String verCode, String verCodeKey, String forget) {

        String reg = "/member/reg/sendsms";//注册
        String reset = "/member/user/sendsms";//重置密码
        String url = Strings.isNullOrEmpty(forget) ? reg : reset;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phone", phone);
        jsonObject.put("verCode", verCode);
        jsonObject.put("verCodeKey", verCodeKey);
        String res = null;
        try {
            res = HttpClientUtil.post(configInfo.getServiceInterfaceAddress() + url, jsonObject);
            System.out.println(res);
        } catch (IOException e) {
            return new Result(true, "短信发送失败");
        }

        JSONObject parseObject = JSON.parseObject(res);
        if (parseObject.getBooleanValue("succ")) {
            return new Result(true, "短信发送成功");
        }

        String msg = ApiCodeToMessageUtil.codeToMessage(parseObject.getString("code"));
        msg = Strings.isNullOrEmpty(msg) ? "短信发送失败" : msg;
        return new Result(false, msg);
    }

    @Override
    public Result sendValidateCode(String smsType, String telNum, String content, long expireSeconds) throws IOException {
        String _key = String.format("sms:code:%s:%s", smsType, telNum);
        long _expires = getExpires(_key);
        if (_expires > 0) {
            return new Result(Result.FAILURE, String.format("请%s秒后重新获取！", _expires));
        } else {
            long _code;
            do {
                _code = new Random(System.currentTimeMillis()).nextInt(1000000);
            } while (_code < 100000);
            //重新请求一次并返回结果
            SMSMessage smsMessage = new SMSMessage();
            smsMessage.setReceiver(telNum);
            content = !Strings.isNullOrEmpty(content) ? content + _code : String.format(Constant.REGISTER_MSG, _code);
            smsMessage.setContent(content);
            String resp = HttpClientUtil.doPostString(configInfo.getSmsSendUrl(), smsMessage);
            //判断是否为空
            if (StringUtils.isNotBlank(resp)) {
                JSONObject data = JSON.parseObject(resp);
                boolean succ = "true".equalsIgnoreCase(data.getString("succ"));
                //是否请求成功
                if (succ) {
                    super.cache(_key, String.valueOf(_code), expireSeconds);
                    return new Result(Result.SUCC, "验证码获取成功");
                } else {
                    return new Result(Result.FAILURE, data.getString("msg"), "验证码获取失败");
                }
            }
            return new Result(Result.FAILURE, "验证码获取失败");
        }
    }
}
